#!/bin/bash
# 一键配置脚本 for NagaAgent 3.0 (Bash 极简版)
set -euo pipefail  # 严格错误处理

pythonMinVersion="3.8"
venvPath=".venv"

# 检查 Python 版本
pythonVersion=$(python3 -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')
if printf "%s\n%s" "$pythonMinVersion" "$pythonVersion" | sort -V -C 2>/dev/null; then
    echo "需要 Python $pythonMinVersion+，当前版本: $pythonVersion" >&2
    exit 1
fi

# 设置工作目录
scriptDir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)
cd "$scriptDir"

# 创建并激活虚拟环境
[ ! -d "$venvPath" ] && python3 -m venv "$venvPath"
source "$venvPath/bin/activate"

# 安装依赖（清华源加速）
echo "安装依赖（使用清华镜像源加速）..."
export PIP_INDEX_URL="https://pypi.tuna.tsinghua.edu.cn/simple"

if [ -f "pyproject.toml" ]; then
    if command -v uv &>/dev/null; then
        uv pip sync 2>&1 | grep -v 'already installed'
    else
        pip install -e . 2>&1 | grep -v 'already installed'
    fi
elif [ -f "requirements.txt" ]; then
    pip install -r requirements.txt 2>&1 | grep -v 'already installed'
else
    echo "未找到依赖文件，请检查项目配置" >&2
    exit 1
fi

# 安装遗留 requirements 文件
find . -maxdepth 1 -name 'requirements*.txt' ! -name 'requirements.txt' -print0 | \
    xargs -0 -I{} pip install -r {} 2>&1 | grep -v 'already installed'

# 安装 Playwright 浏览器驱动
echo "安装 playwright 浏览器驱动..."
python -m playwright install --with-deps chromium

# 验证安装
echo "验证 playwright 安装..."
playwrightVersion=$(python -m playwright --version)
echo "Playwright 版本: $playwrightVersion"

echo "环境设置完成！"
echo "如需安装其他浏览器驱动，请运行:"
echo "python -m playwright install firefox  # 安装 Firefox"
echo "python -m playwright install webkit   # 安装 WebKit"